package com.petshop.controller;

import com.petshop.utils.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
@CrossOrigin
@Slf4j
public class UploadController {

    @Value("${pet_shop.path}")
    private String basePath;

    /**
     * 文件上传
     */
    @PostMapping("/uploadImage")
    public Result uploadImage(MultipartFile file) throws IOException {

        //原始文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用uuid重新生成文件名，防止文件重名造成文件覆盖
        String fileName = UUID.randomUUID() + suffix;
        //创建一个目录对象，判断要存储的目录存不存在
        File directory = new File(basePath);
        if (!directory.exists()) {
            //文件目录不存在，需要创建
            directory.mkdirs();
        }
        //存到（本机）服务器里
        file.transferTo(new File(basePath + fileName));
        log.info(file.toString());
        //返回新的uuid文件名给前端
        return Result.ok(fileName);
    }

    @GetMapping("/downloadImage")
    public void downloadImage(@RequestParam("name") String name, HttpServletResponse httpServletResponse) throws IOException {
        //输入流，通过输入流读取文件内容
        FileInputStream fileInputStream = new FileInputStream(basePath + name);
        //输出流，通过输出流将文件写回浏览器，在浏览器展示图片
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();

        httpServletResponse.setContentType("image/jpeg");

        byte[] buffer = new byte[1024];
        int length;
        while ((length = fileInputStream.read(buffer)) != -1) {
            servletOutputStream.write(buffer, 0, length);
            servletOutputStream.flush();
        }
        servletOutputStream.close();
        fileInputStream.close();
    }
}
